﻿/********************************************************************************
** @ Date:2024/12/30
** @ Author: Gaojia
** @ Description: vlc播放rtsp视频类
** @ Version:1.0.0
** @ Fun:
********************************************************************************/
#ifndef CVlcRtspOper_H
#define CVlcRtspOper_H
#include <QWidget>
#include <QLabel>
#include <QTimer>
#include <QImage>
#include <vlc/vlc.h>
#include <QRunnable>
#include <QThreadPool>
#include <QElapsedTimer>
#include <QReadWriteLock>
#include <QPointer>
#include "CDevDataCam.h"

class FrameProcessor : public QObject, public QRunnable
{
	Q_OBJECT
public:
	explicit FrameProcessor(const QImage &frame, const QSize &targetSize);
	void run() override;

signals:
	void frameProcessed(QPixmap pixmap); // 使用QPointer

private:
	QImage m_frame;
	QSize m_targetSize;
};

class CVlcRtspOper : public QObject
{
	Q_OBJECT
public:
	CVlcRtspOper(CDevDataCam *pDevDataCam,const QString &url, QWidget *pWidget = nullptr);
	~CVlcRtspOper();
	bool startCapture();
	bool stopCapture();

private:
	void init();
	// 自定义回调函数
	static void *lockCallback(void *opaque, void **planes);
	static void unlockCallback(void *opaque, void *picture, void *const *planes);

private slots:
	void slot_CaptureFrame();
	void onFrameProcessed(QPixmap pixmap);
	void safeUpdateUI(QPixmap pixmap);

private:
	CDevDataCam *m_pDevDataCam;
	QString m_sUrl;
	QLabel* m_pImageLabel; // 使用QPointer

	libvlc_media_player_t *m_pMediaPlayer;
	libvlc_media_t *m_pMedia;

	QImage m_cCurrentFrame;
	QImage m_frameBuffer; // 重用缓冲区

	QTimer *m_pFrameTimer;
	bool m_bInit;

	QThreadPool m_threadPool;

	// 帧率控制相关
	qint64 m_lastFrameTime;
	int m_targetFps;
	QElapsedTimer m_frameTimer;
	int m_frameCount;
	int m_actualFps;

	QReadWriteLock m_frameLock; // 使用读写锁
	// 添加原子操作标志
	std::atomic<bool> m_destroying;
};

#endif